package com.lanou3g.ptp.student.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.entity.*;
import com.lanou3g.ptp.organize.service.ClazzService;
import com.lanou3g.ptp.organize.service.CollegeService;
import com.lanou3g.ptp.organize.service.MajorService;
import com.lanou3g.ptp.organize.service.SchoolService;
import com.lanou3g.ptp.student.mapper.StudentMapper;
import com.lanou3g.ptp.student.service.StudentService;
import com.lanou3g.ptp.user.service.UserService;
import com.lanou3g.utils.ExcelUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Reference
    private UserService userService;

    @Reference
    private SchoolService schoolService;

    @Reference
    private ClazzService clazzService;

    @Reference
    private CollegeService collegeService;

    @Reference
    private MajorService majorService;

    //查询所有学生
    @Override
    public PageInfo<Student> findAll(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<Student> students = studentMapper.studentAll();
        studentMapper.studentAll();
        for (Student student : students) {
            //取出user  无密码
            User user = userService.userById(student.getId());
            student.setUser(user);
        }
        return new PageInfo<>(students);
    }


    @Override
    public List<Student> findAll() {
        List<Student> students = studentMapper.studentAll();
        studentMapper.studentAll();
        for (Student student : students) {
            //取出user  无密码
            User user = userService.userById(student.getId());
            student.setUser(user);
        }
        return students;
    }


    //通过id查询
    @Override
    public Student studentById(Long id) {
        return studentMapper.studentById(id);
    }

    //根据名字模糊查询
    @Override
    public PageInfo<Student> ByName(Integer page, Integer size, String name) {
        PageHelper.startPage(page, size);
        List<Student> students = new ArrayList<>();
        List<User> user = userService.userByName(name);
        for (User user1 : user) {
            Student student = studentMapper.studentById(user1.getId());
            student.setUser(user1);
            students.add(student);
        }
        return new PageInfo<>(students);
    }


    //根据id 删除
    @Override
    public int deleteById(Long id) {
        int il = 0;
        int i = userService.deleteById(id);
        if (i > 0) {
            il = studentMapper.deleteById(id);
        }
        return il;
    }

    //根据id 删除多个
    @Override
    public int deleteByIds(List<Long> id) {
        int il = 0;
        for (Long aLong : id) {
            int i = userService.deleteById(aLong);
            if (i > 0) {
                il = studentMapper.deleteById(aLong);
            }
        }
        return il;
    }

    //修改数据
    @Override
    public int upStuById(Long id, Student student) {
        int l = 0;
        Date date = new Date();
        student.setUpdateTime(date);//更新修改时间
        student.getUser().setUpdateTime(date);//更新时间 赋值给用户属性
        student.getUser().setStatus(student.getStatus());//更新时间 赋值给用户属性
        int i = studentMapper.upStudent(id, student);
        User user = student.getUser();
        if (i > 0) {
            try {
                l = userService.upUser(student.getUser());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return l;
    }

    //添加学生
    @Override
    public int insetStudent(Student student) {
        Date date = new Date();
        student.setCreateTime(date);
        student.setUpdateTime(date);
        student.getUser().setCreateTime(date);
        student.getUser().setUpdateTime(date);
        student.getUser().setStatus(0);
        //更新用户
        Long aLong = null;
        try {
            System.out.println("学生user : " + student.getUser());
            aLong = userService.addUser(student.getUser());
            System.out.println("long" + aLong);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //更新学生类
        int l = 0;
        if (aLong != null) {
            l = studentMapper.addStudent(student, aLong);
        }
        return l;
    }

    //导入学生excel
    @Override
    public boolean excelToStudentInfo(byte[] bytes) {
        //把字节数组转回流
        InputStream studentUploadFile = new ByteArrayInputStream(bytes);
        ArrayList<Student> students = new ArrayList<>();
        try {
            Workbook wb = new XSSFWorkbook(studentUploadFile);
            //获取第0页信息
            Sheet sheet = wb.getSheetAt(0);
            if (sheet != null) {
                // rowNum 从第几行开始
                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    System.out.println("循环上限: " + sheet.getLastRowNum());
                    Row row = sheet.getRow(rowNum);
                    Student student = new Student();//创建学生存储每次循环信息
                    student.setHead("默认图片地址");
                    User user = new User();
                    //学号 名字 电话 学校id 学院id 专业id 班级id
                    //获取表格学号属性
                    String noExcel = ExcelUtil.getCellValue(row.getCell(0));
                    user.setNo(noExcel);  //放入对象
                    //获取名字
                    String nameExcel = ExcelUtil.getCellValue(row.getCell(1));
                    user.setName(nameExcel);
                    //获取电话
//                    row.getCell(2).setCellType(CellType.STRING);
//                    String telExcel = row.getCell(2).getStringCellValue();
                    String telExcel = ExcelUtil.getCellValue(row.getCell(2));
                    user.setTel(telExcel);
                    //获取获取学校名字
                    String schoolNameExcel = ExcelUtil.getCellValue(row.getCell(3));
                    School school = schoolService.findByName(schoolNameExcel);
                    student.setSchoolId(school.getId());
                    //获取学院名字
                    String collegeNameExcel = ExcelUtil.getCellValue(row.getCell(4));
                    College college = collegeService.findByName(collegeNameExcel);
                    student.setCollegeId(college.getId());
                    //获取专业名字
                    String majorNameExcel = ExcelUtil.getCellValue(row.getCell(5));
                    Major majorId = majorService.findByName(majorNameExcel);
                    student.setMajorId(majorId.getId());
                    //获取班级名
                    String clazzNameExcel = ExcelUtil.getCellValue(row.getCell(6));
                    Clazz clazz = clazzService.findByName(clazzNameExcel);
                    student.setClazzId(clazz.getId());
                    //user放入对象
                    student.setUser(user);
                    //放进集合
                    students.add(student);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //导入表格
        return studentExcel(students);
    }

    //表格数据 加入数据库
    @Override
    public boolean studentExcel(List<Student> students) {
        //记录 加入条数总数
        int sum = 0;
        boolean b = false;
        //加入数据
        for (Student student : students) {
            int i = insetStudent(student);
            sum += i;
        }
        //判定是否加入条数和信息总数一直  返回结果
        if (sum == students.size()) {
            b = true;
        }
        return b;
    }

    //导出模板
    @Override
    public byte[] excelStudentModel() {

        XSSFWorkbook sheets = new XSSFWorkbook();
        Sheet sheet = sheets.createSheet("码页");

        //负责表格对齐方式
        CellStyle cellStyle1 = sheets.createCellStyle();
        cellStyle1.setAlignment(HorizontalAlignment.LEFT);//设置单元格水平方向对齐方式  居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);//设置单元格垂直方向对齐方式  居中

        //设置表头字体样式
        XSSFCellStyle cellStyle4 = sheets.createCellStyle();
        XSSFFont font1 = sheets.createFont();  //设置字体样式
        font1.setFontName("微软雅黑");
        font1.setFontHeightInPoints((short) 12);//设置字号
        font1.setColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());//设置字体颜色
        cellStyle4.setFont(font1);  //字体风格放入  风格

        Row row1 = sheet.createRow(0);
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(4, 20 * 256);
        sheet.setColumnWidth(5, 20 * 256);
        sheet.setColumnWidth(6, 15 * 256);
        row1.setHeightInPoints(30);//设置行的高度是50
        row1.createCell(0).setCellValue("学号");
        row1.createCell(1).setCellValue("名字");
        row1.createCell(2).setCellValue("电话");
        row1.createCell(3).setCellValue("学校");
        row1.createCell(4).setCellValue("学院");
        row1.createCell(5).setCellValue("专业");
        row1.createCell(6).setCellValue("班级");
        row1.setRowStyle(cellStyle1);
        row1.setRowStyle(cellStyle4);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            sheets.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return os.toByteArray();
    }

    //查询当前班级有多少人
    @Override
    public Long findClazzId(long clazzId) {
        Long clazzId1 = studentMapper.findClazzId(clazzId);
        System.out.println(clazzId1);
        return clazzId1;
    }

}
